﻿using System;
using System.Collections.Generic;
using System.Text;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Json;
using UtilZ.Dotnet.Ex.Model;

namespace UtilZ.Dotnet.Ex.Communication.Net.Web
{
    /// <summary>
    /// web序列化器提供类
    /// </summary>
    public class DefaultWebSerializer : WebSerializerAbs
    {
        private static DefaultWebSerializer _default = null;
        /// <summary>
        /// 获取默认序列化器
        /// </summary>
        public static DefaultWebSerializer Default
        {
            get
            {
                if (_default == null)
                {
                    _default = new DefaultWebSerializer();
                }

                return _default;
            }
        }






        private readonly JsonSerializeSetting _jsonSerializeSetting;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DefaultWebSerializer()
            : base()
        {
            this._jsonSerializeSetting = new JsonSerializeSetting();
        }






        /// <summary>
        /// 将对象序列化为xml
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>xml</returns>
        protected override string PrimitiveXmlSerialize(object obj)
        {
            return SerializeEx.XmlSerializer(obj);
        }

        /// <summary>
        /// 将xml反序列化为指定类型的对象
        /// </summary>
        /// <param name="xml">xml</param>
        /// <param name="targetType">目标类型</param>
        /// <returns>结果对象</returns>
        protected override object PrimitiveXmlDeserialize(string xml, Type targetType)
        {
            return SerializeEx.XmlDeserializerFromString(xml, targetType);
        }

        /// <summary>
        /// 将对象序列化为json
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>json</returns>
        protected override string PrimitiveJsonSerialize(object obj)
        {
            return JsonSerializer.SerializeObject(obj, this._jsonSerializeSetting);
        }

        /// <summary>
        /// 将json反序列化为指定类型的对象
        /// </summary>
        /// <param name="json">json</param>
        /// <param name="targetType">目标类型</param>
        /// <returns>结果对象</returns>
        protected override object PrimitiveJsonDeserialize(string json, Type targetType)
        {
            return JsonSerializer.DeserializeObject(json, targetType, this._jsonSerializeSetting);
        }

    }
}
